package cn.fiker.BeautyPic.http;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.SocketTimeoutException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Iterator;

import cn.fiker.BeautyPic.Consts;
import cn.fiker.BeautyPic.Log;
import cn.fiker.BeautyPic.R;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;

/**
 * HTTP请求类
 * 
 * @author liuqs
 * 
 */
public final class HttpWorker {

	/**
	 * 参数集合
	 */
	private ArrayList<Parameter> paraList = new ArrayList<Parameter>();

	/**
	 * 设置API路径
	 * 
	 * @param module
	 *            模块名
	 * @param function
	 *            函数名
	 * @return
	 */
	public static String setPath(String module, String function) {
		return Consts.api_root + module + "/" + function;
	}

	/**
	 * 发起HTTP请求，获取api数据
	 * 
	 * @param path
	 *            api路径
	 * @param para
	 *            api参数
	 * @return
	 */
	public static String sendRequest(String path, String para) {

		HttpURLConnection httpUrl;
		InputStreamReader bis;
		BufferedReader in;
		String pageContent;
		String line;

		try {
			URL url = new URL(path + para + "/r/" + Math.random());
			
			Log.i(Consts.sysTag, "URL=>" + url.toString());

			httpUrl = (HttpURLConnection) url.openConnection();
			httpUrl.setConnectTimeout(Consts.ConnectTimeOut);
			httpUrl.setReadTimeout(Consts.ReadTimeOut);
			httpUrl.connect();
			bis = new InputStreamReader(httpUrl.getInputStream());

			in = new BufferedReader(bis);
			pageContent = "";
			while (((line = in.readLine()) != null)) {
				pageContent += line;
			}
			return pageContent;
		} catch (SocketTimeoutException e) {
			e.printStackTrace();
		} catch (MalformedURLException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return "";
	}

	/**
	 * 载入网络图片 如果成功，返回图片的Bitmap对象 如果失败，则返回载入失败的图片Bitmap对象
	 * 
	 * @param context
	 * @param picUrl
	 * @param fileName
	 * @return
	 */
	public static Bitmap loadPictuer(Context context, String picUrl,
			String fileName) {

		// 修正路径格式
		if (fileName != null) {
			if (!fileName.startsWith("/")) {
				Consts.CACHE_ITEM_DIR += "/";
			}
		}
		if (!Consts.CACHE_ITEM_DIR.startsWith("/")) {
			Consts.CACHE_ITEM_DIR = "/" + Consts.CACHE_ITEM_DIR;
		}

		// 定位图片保存位置
		String strFolder = Consts.CACHE_ROOT + Consts.CACHE_DIR
				+ Consts.CACHE_ITEM_DIR;
		File folder = new File(strFolder);
		// 如果缓存目录不存在，则创建目录
		if (!folder.exists()) {
			folder.mkdirs();
		}
		// 定位图片文件名
		String strFileName = strFolder + fileName;
		File file = new File(strFileName);
		Bitmap bitmap;
		FileOutputStream fos;
		int fileSize;

		// 如果文件存在，直接返回文件的Bitmap对象
		if (file.exists()) {
			bitmap = BitmapFactory.decodeFile(strFileName);
			return bitmap;
		}

		try {
			// 从网络下载图片
			URL url = new URL(picUrl);
			HttpURLConnection conn = (HttpURLConnection) url.openConnection();
			InputStream is;
			conn.setConnectTimeout(Consts.ConnectTimeOut);
			conn.setReadTimeout(Consts.ReadTimeOut);
			conn.connect();
			fileSize = conn.getContentLength();
			is = conn.getInputStream();
			fos = new FileOutputStream(strFileName);

			// 下载失败则返回“载入失败”图片的Bitmap对象
			if (is == null) {
				bitmap = BitmapFactory.decodeResource(context.getResources(),
						R.drawable.app_load_failed);
				return bitmap;
			}

			// 文件下载不全，也返回“载入失败”图片的Bitmap对象
			if (fileSize <= 0) {
				bitmap = BitmapFactory.decodeResource(context.getResources(),
						R.drawable.app_load_failed);
				return bitmap;
			}

			byte buf[] = new byte[1024];
			do {
				int numread = is.read(buf);
				if (numread == -1) {
					break;
				}
				fos.write(buf, 0, numread);
			} while (true);

			bitmap = BitmapFactory.decodeFile(strFileName);

			fos.close();
			is.close();
			conn.disconnect();

		} catch (SocketTimeoutException e) {
			// 如果出现IOException，也返回“载入失败”图片的Bitmap对象
			bitmap = BitmapFactory.decodeResource(context.getResources(),
					R.drawable.app_load_failed);
			e.printStackTrace();
		} catch (IOException e) {
			// 如果出现IOException，也返回“载入失败”图片的Bitmap对象
			bitmap = BitmapFactory.decodeResource(context.getResources(),
					R.drawable.app_load_failed);
			e.printStackTrace();
		}
		return bitmap;
	}
	

	/**
	 * 增加参数
	 * 
	 * @param key
	 * @param value
	 */
	public void pushPara(String key, String value) {
		paraList.add(new Parameter(key, value));
	}

	/**
	 * 增加参数
	 * 
	 * @param key
	 * @param value
	 */
	public void pushPara(String key, int value) {
		paraList.add(new Parameter(key, "" + value));
	}

	/**
	 * 清空参数
	 */
	public void clearPara() {
		paraList.clear();
	}

	/**
	 * 生成参数串
	 * 
	 * @return
	 */
	public String makePara() {
		if (paraList != null && paraList.size() != 0) {
			String para = "";

			Parameter temp;
			Iterator<Parameter> iterator = paraList.iterator();
			while (iterator.hasNext()) {
				temp = iterator.next();
				para += makePara(temp.key, temp.value);
			}
			return para;
		} else {
			return "";
		}
	}

	/**
	 * 生成参数串
	 * 
	 * @param key
	 * @param value
	 * @return
	 */
	public String makePara(String key, String value) {
		return "/" + key + "/" + value;
	}
}
